import {
    setToken,
    getToken,
    // canTurnTo,
    isLowerIEVersion,
    setTitle
} from '@/utils/index'

import router from './router'
import store from './store'
import {
    Message
} from 'element-ui'
// import storage from '@/utils/localStorage'
const whiteList = ['/login', '/'] // no redirect whitelist

router.beforeEach((to, from, next) => {
    // start progress bar
    let { token, userId } = to.query
    // 兼容IE
    if (isLowerIEVersion() && to.name !== 'download') {
        next({ name: 'download' })
        return
    }
    // 首次登录设置token
    setTitle(to)
    if (token || getToken()) {
        token && setToken(token)
    }
    token = token || getToken()
    if (token) {
        if (to.path === '/login') {
            next()
            return
        }
        const hasRoles = store.getters['user/roles'] && store.getters['user/roles'].length > 0
        if (hasRoles) {
            next()
        } else {
            try {
                // 权限数组: ['admin'] or ,['developer','editor']
                userId = userId || store.getters['user/userInfo'].userId || 1
                store.dispatch('user/setLoginToken', { token, userId }).then(roles => {
                    store.dispatch('permission/generateRoutes', roles).then(accessRoutes => {
                        router.addRoutes(accessRoutes)
                        next({
                            ...to,
                            replace: true
                        })
                    })
                })
            } catch (error) {
                store.dispatch('user/resetToken').then(res => {
                    // Message.error(error || 'Has Error')
                    next(`/login?redirect=${to.path}`)
                })
            }
        }
    } else {
        if (whiteList.indexOf(to.path) !== -1) {
            next()
        } else {
            next(`/login?redirect=${to.path}`)
        }
    }
})

router.afterEach(() => {
})
